package rahmath.sharif.docrypt;

import rahmath.sharif.docrypt.constant.DocryptConstants;
import rahmath.sharif.docrypt.util.AESCryptor;
import rahmath.sharif.docrypt.util.DocryptUtil;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity implements DocryptConstants {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	public void vaults(View view) {
		Intent vaultsIntent = new Intent(this, VaultsActivity.class);
		startActivity(vaultsIntent);
	}

	public void docryptDrive(View view) {
		if (getSharedPreferences("Docrypt", MODE_PRIVATE).getString(
				DOCRYPT_DRIVE_PASSWORD, "").equals("")) {
			Intent drivePasswordIntent = new Intent(MainActivity.this,
					DocryptDrivePasswordActivity.class);
			startActivity(drivePasswordIntent);
			return;
		}
		LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
		final View authenticationView = inflater.inflate(
				R.layout.alert_dialog_vault_authentication, null);
		final EditText editTextPassword = ((EditText) authenticationView
				.findViewById(R.id.editTextAlertVaultPassword));
		editTextPassword.setOnFocusChangeListener(new OnFocusChangeListener() {
			public void onFocusChange(View v, boolean hasFocus) {
				editTextPassword.post(new Runnable() {
					public void run() {
						InputMethodManager inputMethodManager = (InputMethodManager) MainActivity.this
								.getSystemService(Context.INPUT_METHOD_SERVICE);
						inputMethodManager.showSoftInput(editTextPassword,
								InputMethodManager.SHOW_IMPLICIT);
					}
				});
			}
		});
		editTextPassword.requestFocus();
		final DialogInterface.OnClickListener passwordDialogListener = new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				String userEnteredPassword = editTextPassword.getText()
						.toString();
				switch (which) {
				case DialogInterface.BUTTON_POSITIVE:
					if (AESCryptor.validatePassword(256,
							getSharedPreferences("Docrypt", MODE_PRIVATE)
									.getString(DOCRYPT_DRIVE_PASSWORD, ""),
							userEnteredPassword)) {
						Intent intent = new Intent(MainActivity.this,
								Explorer.class);
						intent.putExtra(INTENT_EXTRA_CHOOSE, CHOOSE_ANY);
						intent.putExtra(INTENT_EXTRA_DOCRYPT_DRIVE,
								DOCRYPT_DRIVE);
						intent.putExtra(INTENT_EXTRA_FILE_PATH,
								DocryptUtil.getDocryptDir(DOCRYPT_DRIVE_FOLDER));
						intent.putExtra(INTENT_EXTRA_FILE_PATH_IS_GRAND_PARENT,
								true);
						intent.putExtra(DOCRYPT_DRIVE_PASSWORD,
								userEnteredPassword);
						startActivity(intent);
					} else {
						Toast.makeText(
								getApplicationContext(),
								getString(R.string.docryptDriveAuthenticationFailed),
								Toast.LENGTH_SHORT).show();
						dialog.dismiss();
					}
					break;
				case DialogInterface.BUTTON_NEGATIVE:
					dialog.dismiss();
					break;
				}
			}
		};
		new AlertDialog.Builder(MainActivity.this).setCancelable(false)
				.setTitle("Docrypt Drive").setMessage("Enter the password : ")
				.setPositiveButton("Authenticate", passwordDialogListener)
				.setNegativeButton("Cancel", passwordDialogListener)
				.setView(authenticationView).show();
	}

	public void cryptFile(View view) {
		Intent cryptFileIntent = new Intent(this, CryptFileActivity.class);
		startActivity(cryptFileIntent);
	}

	public void fileCode(View view) {
		Intent cryptFileIntent = new Intent(this, FileCodeActivity.class);
		startActivity(cryptFileIntent);
	}

	public void cryptText(View view) {
		Intent cryptTextIntent = new Intent(this, CryptTextActivity.class);
		startActivity(cryptTextIntent);
	}

	public void textCode(View view) {
		Intent cryptFileIntent = new Intent(this, TextCodeActivity.class);
		startActivity(cryptFileIntent);
	}

	public void cryptClipText(View view) {
		LayoutInflater infalter = LayoutInflater.from(MainActivity.this);
		final View authenticationView = infalter.inflate(
				R.layout.alert_dialog_vault_authentication, null);
		final EditText editTextVaultPassword = ((EditText) authenticationView
				.findViewById(R.id.editTextAlertVaultPassword));
		editTextVaultPassword
				.setOnFocusChangeListener(new OnFocusChangeListener() {
					public void onFocusChange(View v, boolean hasFocus) {
						editTextVaultPassword.post(new Runnable() {
							public void run() {
								InputMethodManager inputMethodManager = (InputMethodManager) MainActivity.this
										.getSystemService(Context.INPUT_METHOD_SERVICE);
								inputMethodManager.showSoftInput(
										editTextVaultPassword,
										InputMethodManager.SHOW_IMPLICIT);
							}
						});
					}
				});
		editTextVaultPassword.requestFocus();
		final DialogInterface.OnClickListener passwordDialogListener = new DialogInterface.OnClickListener() {
			@SuppressWarnings("deprecation")
			@TargetApi(11)
			public void onClick(DialogInterface dialog, int which) {
				String userEnteredPassword = editTextVaultPassword.getText()
						.toString();
				String clipString = null;
				String cryptedClipString = null;
				String label = null;
				android.text.ClipboardManager textClipboardManager = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
					ClipboardManager contentClipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
					clipString = contentClipboardManager.getPrimaryClip()
							.getItemAt(0).coerceToText(MainActivity.this)
							.toString();
				} else {
					if (textClipboardManager.hasText()) {
						clipString = textClipboardManager.getText().toString();
					} else {
						clipString = "";
					}
				}
				if ("".equals(clipString)) {
					Toast.makeText(getApplicationContext(),
							getString(R.string.clipBoardEmpty),
							Toast.LENGTH_SHORT).show();
				}
				switch (which) {
				case DialogInterface.BUTTON_POSITIVE:
					cryptedClipString = AESCryptor.encrypt(256,
							userEnteredPassword, clipString);
					label = "Encrypted Text";
					break;
				case DialogInterface.BUTTON_NEGATIVE:
					cryptedClipString = AESCryptor.decrypt(256,
							userEnteredPassword, clipString);
					label = "Decrypted Text";
					break;
				}
				if (null == cryptedClipString) {
					cryptedClipString = clipString;
					Toast.makeText(getApplicationContext(),
							getString(R.string.clipBoardCryptingFailed),
							Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(getApplicationContext(),
							getString(R.string.clipBoardCryptingSuccessful),
							Toast.LENGTH_SHORT).show();
				}
				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
					ClipboardManager contentClipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
					contentClipboardManager.setPrimaryClip(ClipData
							.newPlainText(label, cryptedClipString));
				} else {
					textClipboardManager.setText(cryptedClipString);
				}
			}
		};
		new AlertDialog.Builder(MainActivity.this).setCancelable(true)
				.setTitle("Enter Password")
				.setMessage("Enter the password to encrypt/decrypt.")
				.setPositiveButton("Encrypt", passwordDialogListener)
				.setNegativeButton("Decrypt", passwordDialogListener)
				.setView(authenticationView).show();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.help:
			Intent helpActivity = new Intent(MainActivity.this,
					HelpActivity.class);
			startActivity(helpActivity);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}
